package com.seguriapp.entitieslist.gwt.server;

import static com.google.common.collect.Lists.newArrayList;

import java.util.List;

import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.DispatchException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.restlet.data.MediaType;
import org.restlet.resource.ClientResource;

import com.seguriapp.common.config.GlobalConfigLoader;
import com.seguriapp.common.gwt.server.AbstractSeguriAppHandler;
import com.seguriapp.entities.SeguriAppEntityType;
import com.seguriapp.entitieslist.gwt.shared.GetEntityTypesAction;
import com.seguriapp.entitieslist.gwt.shared.GetEntityTypesResult;

public class GetEntityTypesHandler extends AbstractSeguriAppHandler<GetEntityTypesAction, GetEntityTypesResult> {

  private static final Logger LOGGER = Logger.getLogger(GetEntityTypesHandler.class);

  public Class<GetEntityTypesAction> getActionType() {
    return GetEntityTypesAction.class;
  }

  public GetEntityTypesResult execute(GetEntityTypesAction action, ExecutionContext context) throws DispatchException {

    final GetEntityTypesResult result = new GetEntityTypesResult();
    try {
      final String serverUrl = GlobalConfigLoader.getInstance().getGlobalConfig().getBackEndUrl();
      final String url = serverUrl.concat(GlobalConfigLoader.getInstance().getGlobalConfig().getEntityTypesList());
      final ClientResource resource = new ClientResource(url);
      final String entityTypesListJs = resource.get(MediaType.TEXT_PLAIN).getText();
      LOGGER.info("Data received : \n" + entityTypesListJs);
      result.setEntityTypesList(getJsonDataFromString(entityTypesListJs));
    } catch (Exception e) {
      LOGGER.error("Error obtaining the initial data \n", e);
    }
    return result;
  }

  private List<SeguriAppEntityType> getJsonDataFromString(final String menuLinksListJs) {
    final List<SeguriAppEntityType> entityTypesList = newArrayList();
    final JSONObject root = JSONObject.fromObject(menuLinksListJs);
    JSONArray dataArray = null;
    JSONObject jo = null;
    if (root.has("entityTypeList")) {
      dataArray = root.getJSONArray("entityTypeList");
      if (dataArray != null) {
        for (int i = 0; i < dataArray.size(); i++) {
          jo = dataArray.getJSONObject(i);
          final SeguriAppEntityType entity = processjSONObject(jo);
          if (entity != null){
            entityTypesList.add(entity);
          }
        }
      }
    }
    return entityTypesList;
  }

  private SeguriAppEntityType processjSONObject(final JSONObject jo) {
    if (jo.has("id") && jo.has("name") && jo.has("description")) {
      final SeguriAppEntityType entity = new SeguriAppEntityType();
      entity.setId(jo.getLong("id"));
      entity.setName(jo.getString("name"));
      entity.setDescription(jo.getString("description"));
      return entity;
    }
    return null;
  }

}
